<?php
require_once(Kohana::find_file('vendor','phprpc/phprpc_client'));

/**
 * Created by PhpStorm.
 * User: locove
 * Date: 15-6-30
 * Time: 下午7:04
 */
class Checkstore
{
    public static $lists = array();
    public $page = NULL;
    public $download = NULL;
    public static $num = 0;

    public function doCondition()
    {
        $sql = checkstore::basicSql($this->download);

        if(empty($this->download)){
            $num = checkstore::getDatas($sql,'num',NULL);

            return checkstore::$num = isset($num[0])&&$num[0]?$num[0]:0;
        }
        checkstore::doAction($sql);
    }

    public function getLimitLists()
    {
        $sql = checkstore::basicSql(1);
        $sql .= " LIMIT ".$this->page->items_per_page." OFFSET ".$this->page->_offset;
        
        checkstore::doAction($sql);
    }

    public function doAction($sql,$type = 1)
    {
        $info = DB::query(Database::SELECT,$sql)
            ->execute('newerp')
            ->as_array('sku');
        $skus = array_keys($info); 
        if(empty($skus)){
            checkstore::$lists = array();
            return;
        }
        $sku_str = "'".implode("','",$skus)."'"; 
        $sql = "SELECT sku,productname FROM vmi_supplier_skus 
            WHERE sku in($sku_str)";
        $skuname = DB::query(Database::SELECT,$sql)
            ->execute('newerp')
            ->as_array('sku');
        $skuname = self::array_columns($skuname,'productname');
        foreach ($info as $key => $value) {
            $place[$value['sku']] = Skusystemapi::getSkuPlacesForVMI($value['sku'],$value['warehouseid']);
        }
        $res = Skusystemapi::getSkuAndStatus($skus);
        foreach ($res as $key => $value) {
            $status[$value['sku']] = $value['status'];
        }

        $lends = checkstock::getLendsNums($skus);

        if($type){
            foreach($skus as $k => $sku){
                checkstore::$lists[$k]['sku']     = $sku;
                checkstore::$lists[$k]['name']    = isset($skuname[$sku])?$skuname[$sku]:'';
                checkstore::$lists[$k]['storage'] = isset($place[$sku])?$place[$sku]:'';
                $warehouseid =  isset($info[$sku]['warehouseid'])?$info[$sku]['warehouseid']:'';
                checkstore::$lists[$k]['warehouseid'] = $warehouseid;
                $stocks = Inventory::get_sku_real_stocks(array($sku), array('warehouse_id'=>$warehouseid));
                checkstore::$lists[$k]['stock']   = isset($stocks[$sku])?$stocks[$sku]:0;
                checkstore::$lists[$k]['lend']    = isset($lends[$sku])?$lends[$sku]:0;
                checkstore::$lists[$k]['status'] = isset($status[$sku])?$status[$sku]:'';
            }
        }else{
            $lists = array();
            foreach($skus as $sku){
                $lists[$sku]['sku']     = $sku;
                $lists[$sku]['name']    = isset($skuname[$sku])?$skuname[$sku]:'';
                $lists[$sku]['storage'] = isset($place[$sku])?$place[$sku]:'';
                $warehouseid = isset($info[$sku]['warehouseid'])?$info[$sku]['warehouseid']:'';
                $stocks = Inventory::get_sku_real_stocks(array($sku), array('warehouse_id'=>$warehouseid));
                $lists[$sku]['warehouseid'] = $warehouseid;
                $lists[$sku]['stock']   = isset($stocks[$sku])?$stocks[$sku]:0;
                $lists[$sku]['lend']    = isset($lends[$sku])?$lends[$sku]:0;
                $lists[$sku]['status']  = isset($status[$sku])?$status[$sku]:'';
            }
            return $lists;
        }
    }

    public static function basicSql($c = NULL)
    {
        $cols = !empty($c)?"upper(`p`.`sku`) `sku` , `p`.`warehouseid`":"count(1) as num";
        $sku_str = '';
        $storage_position = $_GET['storage_position'];
        empty($_GET['storage_position'])||$sku_str = " WHERE sku IN(SELECT DISTINCT sku FROM warehouseorders WHERE storage_position LIKE '{$storage_position}%')";
        $sql  = "SELECT
             {$cols}
        FROM (
        SELECT sku,warehouseid,id FROM sku_stocks $sku_str GROUP BY sku,warehouseid
        ) p
        WHERE 1=1 ";
        empty($_GET['sku'])||$sql .= "AND `p`.`sku` = '".strtoupper(trim($_GET['sku']))."' ";
        empty($_GET['warehouseid'])||$sql .= "AND `p`.`warehouseid` = '".strtoupper(trim($_GET['warehouseid']))."' ";
        $sql .= " ORDER BY id DESC";
        return $sql;
    }

    public static function getClient()
    {
        $client = new PHPRPC_Client();
        $client->useService("http://192.168.5.5:802/profitapi/execute");

        return $client;
    }

    public static function getDatas($sql,$val = NULL,$key = 'sku')
    {
        $results = DB::query(Database::SELECT,$sql)
            ->execute('newerp')
            ->as_array();
        return checkstore::array_columns($results,$val,$key);
    }

    //计算实时库存
    public static function countStock($skus,$date = NULL)
    {
        if(empty($skus)) return false;
        $skus = "'".implode("','",$skus)."'";
        $sql = "SELECT sku,sku_qty 
                FROM stock_order
                WHERE sku IN($skus)";
        $actuals = self::getDatas($sql,'sku_qty','sku');
        return $actuals;
    }

    /**
     * @param $data表格数据
     * @return mixed
     * 检查表格里必须填写的几项是否准确
     */
    public static function checkxls($data)
    {
        $str = '';
        $num = count($data);
        for($i = 2;$i<=$num;$i++){
            $_str     = '';
            $sku      = strtoupper(trim($data[$i]['A']));
            $pd_time  = trim($data[$i]['F']);
            $quantity = trim($data[$i]['H']);
            if($i>2){
                if($sku==trim($data[$i-1]['A'])){
                    $_str .= '你输入的第'.($i-1).'行和第'.$i."行重复，只提交了该SKU的第一个;<br/>";
                }
            }
            if(!isset($sku)||empty($sku)){
                $_str .= '你输入的第'.$i."行SKU不能为空<br/>";
            }

            if(!isset($pd_time)||empty($pd_time)){
                $_str .= '你输入的第'.$i."行盘点时间为空<br/>";
            }

            if(empty($quantity)&&!($quantity==='0')){
                $_str .= '你输入的第'.$i."行盘点量不能为空<br/>";
            }

            if(!preg_match('/^([1-2][0-9]{3})[\/|\-](0?[1-9]|10|11|12)[\/|\-]([1-2]?[0-9]|0[1-9]|30|31)$/',$pd_time)){
                echo $pd_time;
                $_str .= '你输入的第'.$i."行盘点日期不符合规则<br/>";
            }

            if(!preg_match('/^(\d+)?$/',$quantity)){
                $_str .= '你输入的第'.$i."行数量不符合规则<br/>";
            }

            if(!Deliverycheck::check_sku($sku)){
                $_str .= '你输入的第'.$i."行SKU有误<br/>";
            }

            if($_str!=''){
                unset($data[$i]);
            }
            $str .= $_str;
        }
        $data['error'] = $str;
        return $data;
    }

    //上传盘点单
    public function upload($data,$time)
    {

        $error       = '';
        $lines       = array();
        $count       = count($data);
        $user_id     = User::active_user()->id;
        $now = date('Y-m-d H:i:s');
        $skus_arr = array();
        foreach ($data as $key => $value){
            $skus_arr[] = strtoupper(trim($value['sku']));
        }
        $prices = checkstore::getSkuPrice($skus_arr);
        $i=0;
        foreach ($data as $key => $value) {
            $i++;
            $sku           = strtoupper(trim($value['sku']));
            $download_time = trim($value['download_time']);
            $upload_time   = date('Y-m-d H:i:s');
            $warehouseid   = $value['warehouseid'];
            $quantity      = trim($value['quantity']);
            $quantity2     = trim($value['quantity2']);
            $pd_time       = trim($value['pd_time']);

            try{
                $stocks = Inventory::get_sku_real_stocks(array($sku), array('warehouse_id'=>$value['warehouseid']));
                $quantity3 = isset($stocks[$sku])?$stocks[$sku]:0;
                $num       = $quantity-$quantity2; //实际盘点量-下载表格时的库存量
                //$status 3:盘点数量相等，1：盘亏，2：盘赢
                $status = 3;
                if($num>0){
                    $status = 2;
                }elseif($num<0){
                    $status = 1;
                }

                $info                     = array();
                $info['sku_name']         = trim($value['sku_name']);
                $info['sku_standard']     = '';
                $info['storage_position'] = trim($value['storage_position']);
            }catch(Exception $e){
                $error .= '第'.$i.'行SKU:'.$sku."SKU信息找不到没有插入";
                continue;
            }
            try{
                list($insert_id,) = DB::insert('pandians',array(
                        'warehouseid',
                        'sku',
                        'sku_name',
                        'storage_position',
                        'sku_standard',
                        'quantity',
                        'quantity2',
                        'quantity3',
                        'pd_time',
                        'op_time',
                        'download_time',
                        'upload_time',
                        'user_id',
                        'status',
                        'num'
                    ))
                    ->values(array(
                        $warehouseid,
                        $sku,
                        $info['sku_name'],
                        $info['storage_position'],
                        $info['sku_standard'],
                        $quantity,
                        $quantity2,
                        $quantity3,
                        $pd_time,
                        $time,
                        $download_time,
                        $upload_time,
                        $user_id,
                        $status,
                        $num
                    ))
                    ->execute('newerp');
            }catch(Exception $e){
                $error .= '第'.$i.'行SKU:'.$sku."当天已经插入;错误信息：$e->getMessage()<br/>";
            }

            if(!$insert_id){
                $lines['num'][] = $i;
                continue;
            }else{
                $condition = array(
                    'sku'           => $sku,
                    'delivery_date' => $download_time,
                    'quantity'      => abs($num),
                    'order_id'      => 0
                );
                $condition = array_merge($condition,$info);
                //@todo 需求 vmi系统盘亏要出，盘盈不入
                if($num>0){
                    //盘赢自动入库
                    $condition['warehouseid']  = $warehouseid;
                    $condition['single_price'] = isset($prices[$sku])?$prices[$sku]:0;
                    $condition['remark']       = '盘赢自动入库，盘点单id：'.$insert_id;
                    $condition['type']         = 30;
                    $tempdata = array(
                        "type"=>30, 
                        "sku" => $condition['sku'],
                        "sku_name" =>$condition['sku_name'],
                        "supplier_id"=>0,
                        "sku_quality"=>$condition["quantity"], 
                        "storage_position"=>$condition["storage_position"], 
                        "single_price"=>$condition['single_price'], // 单价
                        "transportation_expense"=>0, 
                        "warehouse_date"=> $now, 
                        "remark"=>"VMI盘盈入库;ID:".$insert_id, 
                        "purchaseorders_id"=>"0",
                    );
                    $res = self::hzWarehouseorders(array($tempdata),$condition['warehouseid']);
                }else{
                    if($num<0){
                        //盘亏自动出库
                        $condition['warehouseid']        = $warehouseid;
                        $condition['single_price']       = 0;
                        $condition['remark']             = '盘亏自动出库，盘点单id：'.$insert_id;
                        $condition['type']               = 20;
                        $condition['orders_products_id'] = 0;
                        $condition['userid']             = $user_id;
                        $condition['pr']                 = isset($prices[$sku])?$prices[$sku]:0;
                        self::insertDelivery($condition);
                        $tempdata = array(
                            "warehouseid" => $condition['warehouseid'],//仓库ID
                            "delivery_date"=> $now,//出库日期
                            "op_time" =>$now,//操作时间
                            "order_id" => '0',//erp订单id
                            "orders_products_id" => "0",//erp产品id
                            "delivery_department" => "VMI项目",//出库部门
                            'delivery_man' => '2',
                            "supplier_id" => 0,//供应商id
                            "sku"=> $condition['sku'],//sku
                            "sku_name"=>$condition['sku_name'],//sku名字
                            "sku_standard"=>$condition['sku_standard'],
                            "storage_position"=>$condition['storage_position'],
                            "quantity"=>$condition["quantity"], 
                            "single_price"=>$condition["single_price"], 
                            "money" => $condition["single_price"]*$condition["quantity"],
                            "cost" => 0,//成本
                            "internationalship_cost"=>'0',//国际运费
                            "remark"=>"VMI盘亏出库;ID:".$insert_id, 
                            "type"=>'20',
                        );
                        $res = self::hzDeliveryorders(array($tempdata),$condition['warehouseid']);
                    }
                }
            }
        }
        unset($stocks,$prices);
        $lines['error'] = empty($error)?'':"<br/>".$error."以上异常SKU均未上传成功<br/>";
        return $lines;
    }

    //盘亏出库重构 先进先出
    public static function insertDelivery($condition = array()){
        $vmiclass = new Vmiclass();
        $info = array(
            'sku' => $condition['sku'],
            'warehouseid'=>$condition['warehouseid'],
            'enterprise_dominant' => array(3,11,12),
            'quantity' => $condition['quantity'],
            'type' => 20,
            'remark' => 'VMI盘亏出库',
        );
        $available_order = $vmiclass->getAvailableWarehouseorders($info);
        if(!$available_order){
            return false;
        }
        $deliveryInfo = $vmiclass->delivery($info,$available_order);
        return $deliveryInfo;
    }

    //重构获取SKU价格
    public static function getSkuPrice($skus = NULL){
        $re = array();
        if(!empty($skus)){
            $skus = "'".implode("','",$skus)."'";
            $sql = "SELECT sku,price num FROM vmi_supplier_skus 
                    WHERE sku 
                    IN($skus)";
            return checkstore::getDatas($sql,'num','sku');
        }
    }

    public static function array_columns($input,$columnKey,$indexKey = NULL){
        $columnKeyIsNumber = (is_numeric($columnKey))?TRUE:FALSE;
        $indexKeyIsNull = (is_null($indexKey))?TRUE:FALSE;
        $indexKeyIsNumber = (is_numeric($indexKey))?TRUE:FALSE;
        $result = array();

        foreach((array)$input AS $key => $row){
            if($columnKeyIsNumber){
                $tmp = array_slice($row,$columnKey,1);
                $tmp = (is_array($tmp)&&!empty($tmp))?current($tmp):NULL;
            }else{
                $tmp = isset($row[$columnKey])?$row[$columnKey]:NULL;
            }
            if(!$indexKeyIsNull){
                if($indexKeyIsNumber){
                    $key = array_slice($row,$indexKey,1);
                    $key = (is_array($key)&&!empty($key))?current($key):NULL;
                    $key = is_null($key)?0:$key;
                }else{
                    $key = isset($row[$indexKey])?$row[$indexKey]:0;
                }
            }
            $result[$key] = $tmp;
        }

        return $result;
    }

    //调用汇总进销存盘亏出库接口
    public static function  hzDeliveryorders($data,$warehouse_id){
        $host = self::hzApiHost();
        $url = $host.'index.php/commonapi/openwmsapi/outWarehouseorders';
        $data = array(
            'sign' => '91c4b6e5fd80424289f81a1f3d068e49',
            'warehouse_id' => $warehouse_id,
            'data' => $data,
        );
        $res = Baseclass::invoke_curl_org($url,json_encode($data));
        return $res;
    }

    //调用汇总进销存盘盈入库接口
    public static function  hzWarehouseorders($data,$warehouse_id){
        $host = self::hzApiHost();
        $url = $host.'index.php/commonapi/openwmsapi/specialStorage';
        $data = array(
            'sign' => '91c4b6e5fd80424289f81a1f3d068e49',
            'warehouse_id' => $warehouse_id,
            'data' => $data,
        );
        $res = Baseclass::invoke_curl_org($url,json_encode($data));
        return $res;
    }

    public static function hzApiHost(){
        $server_url = Kohana::$config->load('api_url');
        return $server_url['hzerp_host'].'/';
    }
}